# -*- coding:utf8 -*-

import urllib
import urllib2
import cookielib


class MyWeb():
    """
        模拟一个浏览器
    """
    def __init__(self):
        self.header = {
            "User-Agent": "Opera/8.0 (Macintosh; PPC Mac OS X; U; en)",
            "Referer": "https://www.cosven.com"
        }
        self.cookie = cookielib.LWPCookieJar()
        self.cookie_support = urllib2.HTTPCookieProcessor(self.cookie)
        self.opener = urllib2.build_opener(self.cookie_support,
                                           urllib2.HTTPHandler)
        urllib2.install_opener(self.opener)

    def post(self, posturl, dictdata):
        """
        模拟post请求

        :param string posturl: url地址
        :param dict dictdata: 发送的数据
        """

        postdata = urllib.urlencode(dictdata)
        request = urllib2.Request(posturl, postdata, self.header)
        try:
            content = urllib2.urlopen(request)
            return content
        except Exception, e:
            print ("post:" + str(e))
            return None

    def get(self, url):
        """
        模拟get请求

        :param url: url地址
        :return content: 常使用read的方法来读取返回数据
        :rtype : instance or None
        """
        request = urllib2.Request(url, None, self.header)
        try:
            content = urllib2.urlopen(request)
            return content
        except Exception, e:
            print ("open:" + str(e))
            return None


if __name__ == "__main__":
    pass
